#include "QQSqlDatabase.h"

QQSqlDatabase* QQSqlDatabase::getInstance()
{
	static QQSqlDatabase* instance = nullptr;
	if (instance == nullptr)
		instance = new QQSqlDatabase();
	return instance;
}

void QQSqlDatabase::init()
{
	mDatabase = new QSqlDatabase;
}

void QQSqlDatabase::setDriverName(const QString& s)
{
	mDriverName = s;
	mDatabase->setDatabaseName(mDriverName);
}

QString QQSqlDatabase::getDriverName() const
{
	return mDriverName;
}

void QQSqlDatabase::setConnectOptions(const QString& s)
{
	mConnectOptions = s;
	mDatabase->setConnectOptions(mConnectOptions);
}

QString QQSqlDatabase::getConnectOptions() const
{
	return mConnectOptions;
}

void QQSqlDatabase::setDatabaseName(const QString& s)
{
	mDatabaseName = s;
	mDatabase->setDatabaseName(mDatabaseName);
}

QString QQSqlDatabase::getDatabaseName() const
{
	return mDatabaseName;
}

void QQSqlDatabase::setUserName(const QString& s)
{
	mUserName = s;
	mDatabase->setUserName(mUserName);
}

QString QQSqlDatabase::getUserName() const
{
	return mUserName;
}

void QQSqlDatabase::setPassword(const QString& s)
{
	mPassword = s;
	mDatabase->setPassword(mPassword);
}

QString QQSqlDatabase::getPassword() const
{
	return mPassword;
}

void QQSqlDatabase::setHostName(const QString& s)
{
	mHostName = s;
	mDatabase->setHostName(mHostName);
}

QString QQSqlDatabase::getHostName() const
{
	return mHostName;
}

void QQSqlDatabase::setPort(int i)
{
	mPort = i;
	mDatabase->setPort(mPort);
}

int QQSqlDatabase::getPort() const
{
	return mPort;
}

template <class T>
void QQSqlDatabase::registerMetaType()
{
	QMutexLocker locker(&mMutex);
	T mMetaObject;
	const QMetaObject* meta = mMetaObject.metaObject();
	QMap<QString, QString> metaType;
	for (int i = meta->propertyOffset(); i < meta->propertyCount(); ++i)
	{
		QMetaProperty prop = meta->property(i);
		metaType[prop.name()] = prop.typeName();
	}
	mMetaTypeMap.insert(meta->className(), metaType);
}

void QQSqlDatabase::createTable(const QString& id, const QString& relation, const QStringList& key, const QString& name)
{
	QMutexLocker locker(&mMutex);
	QPushButton mMetaObject;
	const QMetaObject* meta = mMetaObject.metaObject();
	if (name == QString())
		mMetaTable.insert(meta->className(), meta->className());
	else
		mMetaTable.insert(meta->className(), name);

	QMap<QString, QString> metaType = mMetaTypeMap[meta->className()];

	QString sql = "CREATE TABLE " + mMetaTable[meta->className()] + " (";
	for (auto it = metaType.begin(); it != metaType.end(); ++it)
	{
		sql += it.key() + " ";
		sql += mSqlTypeMap[it.value()] + ",";
	}
	sql += "PRIMARY KEY (" + id + "),";


	sql += relation + " TEXT, ";
	for (int i = 0; i < key.size(); ++i)
	{
		sql += key[i] + " TEXT, ";
	}
	sql = sql.left(sql.size() - 2);
	sql += ")";
	QSqlQuery query(*mDatabase);
	query.exec(sql);
}

